package com.tzkyzj.tiremanagersystem.ui;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.tzkyzj.tiremanagersystem.R;
import com.tzkyzj.tiremanagersystem.api.TireApiService;
import com.tzkyzj.tiremanagersystem.eneities.Tire;
import com.tzkyzj.tiremanagersystem.network.ApiClient;
import com.tzkyzj.tiremanagersystem.network.ApiResponse;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class EditTireActivity extends AppCompatActivity {

    private TireApiService apiService;
    private Tire currentTire;

    private EditText etTireNumber, etTireBrand, etTireModel;
    private EditText etVehiclePlateNumber, etTrailerPlateNumber, etTransportCompany;
    private EditText etTirePrice, etInstallCost, etInstallMileage;
    private EditText etInstallDate;
    private ProgressBar progressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_tire);

        // 获取传递的轮胎数据
        currentTire = (Tire) getIntent().getSerializableExtra("tire");
        if (currentTire == null) {
            Toast.makeText(this, "轮胎数据获取失败", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        initViews();
        setupRetrofit();
        // 先填充现有数据
        populateFormData();
        // 然后重新加载完整数据
        reloadTireData();
        setupListeners();
    }

    private void initViews() {
        progressBar = findViewById(R.id.progressBar);

        etTireNumber = findViewById(R.id.et_tire_number);
        etTireBrand = findViewById(R.id.et_tire_brand);
        etTireModel = findViewById(R.id.et_tire_model);
        etVehiclePlateNumber = findViewById(R.id.et_vehicle_plate_number);
        etTrailerPlateNumber = findViewById(R.id.et_trailer_plate_number);
        etTransportCompany = findViewById(R.id.et_transport_company);
        etTirePrice = findViewById(R.id.et_tire_price);
        etInstallCost = findViewById(R.id.et_install_cost);
        etInstallMileage = findViewById(R.id.et_install_mileage);
        etInstallDate = findViewById(R.id.et_install_date);

        // 设置轮胎号不可编辑
        etTireNumber.setEnabled(false);
    }

    private void setupRetrofit() {
        // 使用统一的 ApiClient
        Retrofit retrofit = ApiClient.getClient();
        if (retrofit != null) {
            apiService = retrofit.create(TireApiService.class);
            Log.d("EditTireActivity", "使用 ApiClient 创建 API 服务");
        } else {
            Log.e("EditTireActivity", "ApiClient 返回的 Retrofit 为 null");
            // 如果 ApiClient 返回 null，使用原来的方式作为备选
            setupRetrofitFallback();
        }
    }

    /**
     * 备用的 Retrofit 设置方法
     */
    private void setupRetrofitFallback() {
        Log.w("EditTireActivity", "使用备用的 Retrofit 设置");
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://120.55.37.146:8080/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        apiService = retrofit.create(TireApiService.class);
    }

    private void populateFormData() {
        // 调试信息 - 检查所有数值字段
        Log.d("EditTireActivity", "轮胎价格: " + currentTire.getTirePrice() + " (类型: " +
                (currentTire.getTirePrice() != null ? currentTire.getTirePrice().getClass().getSimpleName() : "null") + ")");
        Log.d("EditTireActivity", "安装费用: " + currentTire.getInstallCost() + " (类型: " +
                (currentTire.getInstallCost() != null ? currentTire.getInstallCost().getClass().getSimpleName() : "null") + ")");
        Log.d("EditTireActivity", "安装里程: " + currentTire.getInstallMileage() + " (类型: " +
                (currentTire.getInstallMileage() != null ? currentTire.getInstallMileage().getClass().getSimpleName() : "null") + ")");

        // 填充现有数据到表单
        etTireNumber.setText(currentTire.getTireNumber());
        etTireBrand.setText(currentTire.getTireBrand());
        etTireModel.setText(currentTire.getTireModel());
        etVehiclePlateNumber.setText(currentTire.getVehiclePlateNumber());
        etTrailerPlateNumber.setText(currentTire.getTrailerPlateNumber());
        etTransportCompany.setText(currentTire.getTransportCompany());
        etInstallDate.setText(currentTire.getInstallDate());

        // 设置数值型数据 - 更健壮的版本
        setNumericFieldValue(etTirePrice, currentTire.getTirePrice(), "暂无价格");
        setNumericFieldValue(etInstallCost, currentTire.getInstallCost(), "暂无安装费用");
        setNumericFieldValue(etInstallMileage, currentTire.getInstallMileage(), "暂无安装里程");
    }

    // 辅助方法：设置数值字段的值
    private void setNumericFieldValue(EditText editText, Object value, String hintWhenNull) {
        if (value != null) {
            // 确保转换为字符串
            String stringValue = String.valueOf(value);
            Log.d("EditTireActivity", "设置字段值: " + stringValue);
            editText.setText(stringValue);
        } else {
            Log.d("EditTireActivity", "字段值为null，显示提示: " + hintWhenNull);
            editText.setText("");
            editText.setHint(hintWhenNull);
        }
    }

    private void setupListeners() {
        // 保存按钮点击事件
        findViewById(R.id.btn_save).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveTireInfo();
            }
        });

        // 取消按钮点击事件
        findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void reloadTireData() {
        if (currentTire == null || currentTire.getId() == null) {
            return;
        }

        showLoading(true);

        // 使用正确的API调用方式
        Call<ApiResponse<Tire>> call = apiService.getTireDetail(currentTire.getId());
        call.enqueue(new Callback<ApiResponse<Tire>>() {
            @Override
            public void onResponse(Call<ApiResponse<Tire>> call, Response<ApiResponse<Tire>> response) {
                showLoading(false);
                Log.d("APIDebug", "轮胎详情API响应码: " + response.code());

                // 处理认证失败的情况
                if (response.code() == 401) {
                    handleUnauthorizedError();
                    return;
                }

                if (response.isSuccessful() && response.body() != null) {
                    ApiResponse<Tire> apiResponse = response.body();
                    if (apiResponse.isSuccess() && apiResponse.getData() != null) {
                        // 更新currentTire对象为完整数据
                        Tire updatedTire = apiResponse.getData();
                        currentTire = updatedTire;

                        // 重新填充表单数据
                        populateFormData();

                        // 调试日志
                        Log.d("EditTireDebug", "重新加载后的数据 - " +
                                "轮胎价格: " + currentTire.getTirePrice() +
                                ", 安装费: " + currentTire.getInstallCost() +
                                ", 安装里程: " + currentTire.getInstallMileage());
                    } else {
                        String errorMsg = "获取更新数据失败";
                        if (response.body() != null) {
                            errorMsg += ": " + response.body().getMessage();
                        }
                        Toast.makeText(EditTireActivity.this, errorMsg, Toast.LENGTH_SHORT).show();
                    }
                } else {
                    String errorMsg = "获取更新数据失败，状态码: " + response.code();
                    Toast.makeText(EditTireActivity.this, errorMsg, Toast.LENGTH_SHORT).show();
                    Log.e("EditTireActivity", "获取更新数据失败，状态码: " + response.code());
                }
            }

            @Override
            public void onFailure(Call<ApiResponse<Tire>> call, Throwable t) {
                showLoading(false);
                Log.e("EditTireActivity", "重新加载数据失败", t);
                Toast.makeText(EditTireActivity.this, "加载数据失败: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void saveTireInfo() {
        // 验证必填字段
        if (!validateForm()) {
            return;
        }

        showLoading(true);

        // 构建请求数据
        Map<String, Object> updateData = new HashMap<>();
        updateData.put("id", currentTire.getId());
        updateData.put("tireNumber", etTireNumber.getText().toString().trim());
        updateData.put("tireBrand", etTireBrand.getText().toString().trim());
        updateData.put("tireModel", etTireModel.getText().toString().trim());
        updateData.put("vehiclePlateNumber", etVehiclePlateNumber.getText().toString().trim());
        updateData.put("trailerPlateNumber", etTrailerPlateNumber.getText().toString().trim());
        updateData.put("transportCompany", etTransportCompany.getText().toString().trim());
        updateData.put("installDate", etInstallDate.getText().toString().trim());

        // 处理数值型字段 - 改进版
        try {
            String tirePriceStr = etTirePrice.getText().toString().trim();
            if (!tirePriceStr.isEmpty()) {
                // 用户输入了新值，使用新值
                updateData.put("tirePrice", new BigDecimal(tirePriceStr));
            } else {
                // 用户清空了字段，保持原值不变
                updateData.put("tirePrice", currentTire.getTirePrice());
            }

            String installCostStr = etInstallCost.getText().toString().trim();
            if (!installCostStr.isEmpty()) {
                // 用户输入了新值，使用新值
                updateData.put("installCost", new BigDecimal(installCostStr));
            } else {
                // 用户清空了字段，保持原值不变
                updateData.put("installCost", currentTire.getInstallCost());
            }

            String installMileageStr = etInstallMileage.getText().toString().trim();
            if (!installMileageStr.isEmpty()) {
                // 用户输入了新值，使用新值
                updateData.put("installMileage", Integer.parseInt(installMileageStr));
            } else {
                // 用户清空了字段，保持原值不变
                updateData.put("installMileage", currentTire.getInstallMileage());
            }
        } catch (NumberFormatException e) {
            Toast.makeText(this, "数值格式不正确", Toast.LENGTH_SHORT).show();
            showLoading(false);
            return;
        }

        // 调用API更新轮胎信息
        Call<Map<String, Object>> call = apiService.updateTire(updateData);
        call.enqueue(new Callback<Map<String, Object>>() {
            @Override
            public void onResponse(Call<Map<String, Object>> call, Response<Map<String, Object>> response) {
                showLoading(false);

                // 处理认证失败的情况
                if (response.code() == 401) {
                    handleUnauthorizedError();
                    return;
                }

                if (response.isSuccessful() && response.body() != null) {
                    Map<String, Object> result = response.body();
                    Boolean success = (Boolean) result.get("success");
                    if (success != null && success) {
                        Toast.makeText(EditTireActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
                        setResult(RESULT_OK);
                        finish();
                    } else {
                        String message = (String) result.get("message");
                        Toast.makeText(EditTireActivity.this, "修改失败: " + message, Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(EditTireActivity.this, "修改失败，状态码: " + response.code(), Toast.LENGTH_SHORT).show();
                    Log.e("EditTireActivity", "修改失败，状态码: " + response.code());
                }
            }

            @Override
            public void onFailure(Call<Map<String, Object>> call, Throwable t) {
                showLoading(false);
                Toast.makeText(EditTireActivity.this, "网络错误: " + t.getMessage(), Toast.LENGTH_SHORT).show();
                Log.e("EditTireActivity", "网络错误", t);
            }
        });
    }

    private boolean validateForm() {
        String tireNumber = etTireNumber.getText().toString().trim();
        String tireBrand = etTireBrand.getText().toString().trim();
        String tireModel = etTireModel.getText().toString().trim();

        if (tireNumber.isEmpty()) {
            Toast.makeText(this, "轮胎号不能为空", Toast.LENGTH_SHORT).show();
            return false;
        }

        if (tireBrand.isEmpty()) {
            Toast.makeText(this, "轮胎品牌不能为空", Toast.LENGTH_SHORT).show();
            return false;
        }

        if (tireModel.isEmpty()) {
            Toast.makeText(this, "轮胎型号不能为空", Toast.LENGTH_SHORT).show();
            return false;
        }

        return true;
    }

    private void showLoading(boolean show) {
        progressBar.setVisibility(show ? View.VISIBLE : View.GONE);
        findViewById(R.id.btn_save).setEnabled(!show);
        findViewById(R.id.btn_cancel).setEnabled(!show);
    }

    /**
     * 处理认证失败的情况
     */
    private void handleUnauthorizedError() {
        runOnUiThread(() -> {
            Log.e("AuthError", "Session 认证失败，可能需要重新登录");
            Toast.makeText(EditTireActivity.this, "登录已过期，请重新登录", Toast.LENGTH_LONG).show();

            // 清除用户数据
            SharedPreferences prefs = getSharedPreferences("user_prefs", MODE_PRIVATE);
            prefs.edit().clear().apply();

            // 清除 ApiClient 实例和 Session
            ApiClient.clearClient();

            // 跳转到登录页面
            Intent intent = new Intent(EditTireActivity.this, LoginActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            finish();
        });
    }

    private void updateTireFromResponse(Map<String, Object> data) {
        try {
            // 更新费用字段 - 简单直接的方式
            if (data.get("tirePrice") != null) {
                String tirePriceStr = data.get("tirePrice").toString();
                currentTire.setTirePrice(Double.parseDouble(tirePriceStr));
            }

            if (data.get("installCost") != null) {
                String installCostStr = data.get("installCost").toString();
                currentTire.setInstallCost(Double.parseDouble(installCostStr));
            }

            if (data.get("installMileage") != null) {
                String installMileageStr = data.get("installMileage").toString();
                currentTire.setInstallMileage(Integer.parseInt(installMileageStr));
            }

            Log.d("EditTireDebug", "更新后的数据 - 价格: " + currentTire.getTirePrice() +
                    ", 安装费: " + currentTire.getInstallCost());

        } catch (NumberFormatException e) {
            Log.e("EditTireActivity", "数值格式转换错误", e);
            Toast.makeText(this, "数据格式错误", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Log.e("EditTireActivity", "数据解析错误", e);
            Toast.makeText(this, "数据解析错误", Toast.LENGTH_SHORT).show();
        }
    }
}